//
//  MyWalletViewController.m
//  BGM
//
//  Created by 我要变好看 on 2018/12/11.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "MyWalletViewController.h"
#import "common.h"
#import "BGMHTTP.h"
#import "BGMUser.h"
#import "APAuthInfo.h"

#import <AlipaySDK/AlipaySDK.h>
#import "BGMShareView.h"
#import "SVProgressHUD.h"

#import "CommonView.h"

#import "WalletDetailsViewController.h"
#import "WalletWithdrawViewController.h"

@interface MyWalletViewController ()

@property (nonatomic, strong)NSString *auth_code;
@property (nonatomic, strong)UILabel *moneyLabel;
@property (nonatomic, strong)NSDictionary *aliInfo;

@property (nonatomic, strong)UIView *bgView;
@property (nonatomic, strong)NSString *money;

@end

@implementation MyWalletViewController
- (void)freshUserMoenyNotification{
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId};
    [BGMHTTP requestWithMethodName:@"users/getUsersWallet" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *data = [result objectForKey:@"data"];
                id balance = [data objectForKey:@"userWallt"];
                self.moneyLabel.text = [NSString stringWithFormat:@"￥ %@",balance];
                self.money =  [NSString stringWithFormat:@"%@",balance];
            });
        }else{
            [SVProgressHUD showErrorWithStatus:@"接口请求错误"];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(freshUserMoenyNotification) name:@"freshUserMoenyNotification" object:nil];
    
    self.topBackView.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;
    [self.titleBtn setTitle:@"我的钱包" forState:UIControlStateNormal];
    
    float w = 100;
    float spx = (SCREENW-w*3)/4;
    NSArray *array = @[@"明细",@"余额",@"提现"];
    for (int i =0 ; i<3; i++) {
        BGMShareButton *btn = [[BGMShareButton alloc]initWithFrame:CGRectMake((spx*(i+1))+(w*i), self.navview.frame.size.height+20, w, 90)];
        [btn.imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"money_%d",i]]];
        btn.textLabel.text = [array objectAtIndex:i];
        btn.textLabel.font = [UIFont systemFontOfSize:15];
        btn.textLabel.textColor = bgmmainColor;
        [self.view addSubview:btn];
        btn.tag = 100+i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClickBtn:)];
        [btn addGestureRecognizer:tap];
    }
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height+110, SCREENW, 30)];
    self.moneyLabel.textColor = bgmmainColor;
    self.moneyLabel.font = [UIFont systemFontOfSize:18];
    self.moneyLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.moneyLabel];
 
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 230, SCREENW, SCREENH-230)];
    self.bgView.backgroundColor = bgmColor(244, 244, 244);
    [self.view addSubview:self.bgView];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 40)];
    label1.text = @"提现账户";
    label1.textColor = bgmgrayColor;
    [self.bgView addSubview:label1];
    
    [self getUserMenoy];
    
}

#pragma mark 网络请求
- (void)getUserMenoy{
    [SVProgressHUD show];

    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId};
    [BGMHTTP requestWithMethodName:@"users/getUsersWallet" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            [self addSubviewWithDictior:result];
        }else{
            [SVProgressHUD showErrorWithStatus:@"接口请求错误"];
        }
    }];
}

-(void)addSubviewWithDictior:(NSDictionary *)dic{
    NSDictionary *data = [dic objectForKey:@"data"];
    id balance = [data objectForKey:@"userWallt"];
    self.moneyLabel.text = [NSString stringWithFormat:@"￥ %@",balance];
    self.money =  [NSString stringWithFormat:@"%@",balance];
    
    id aliInfo = [data objectForKey:@"alipayInfo"];
    if ([aliInfo isKindOfClass:[NSDictionary class]]) {
        self.aliInfo = aliInfo;
        [self addAliPay];
    }else{
        self.aliInfo = nil;
        [self addAliPay];
    }
    
   
}
- (void)addAliPay{
    if (self.aliInfo == nil) {
        
        UIView *view = [self.view viewWithTag:10000];
        [view removeFromSuperview];
        
        UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 60, SCREENW-30, 50)];
        [addBtn setTitle:@"+ 添加支付宝提现帐户" forState:UIControlStateNormal];
        addBtn.backgroundColor = bgmColor(224, 224, 224);
        [addBtn setTitleColor:bgmsmallColor forState:UIControlStateNormal];
        addBtn.layer.cornerRadius = 6;
        addBtn.layer.masksToBounds = YES;
        addBtn.tag = 99;
        [addBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.bgView addSubview:addBtn];
    }else{
        [self addAliPayInfo];
    }

}
- (void)addAliPayInfo{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView *view = [self.view viewWithTag:99];
        [view removeFromSuperview];
        UIView *aliView = [[UIView alloc]initWithFrame:CGRectMake(16, 60, SCREENW-30, 80)];
        aliView.layer.cornerRadius = 6;
        aliView.layer.masksToBounds = YES;
        aliView.backgroundColor = [UIColor whiteColor];
        aliView.tag = 10000;
        [self.bgView addSubview:aliView];
        
        UIImageView *aliImage = [[UIImageView alloc]initWithFrame:CGRectMake(15, 15, 60, 50)];
        [aliImage setImage:[UIImage imageNamed:@"payIcon"]];
        [aliView addSubview:aliImage];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(90, 0, 300, 80)];
        label.text = [self.aliInfo objectForKey:@"alipayNickname"];
        label.textColor = bgmgrayColor;
        label.font = [UIFont systemFontOfSize:17];
        [aliView addSubview:label];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickCard)];
        [aliView addGestureRecognizer:tap];
    });
}

- (void)clickBtn:(UIButton *)btn{
    [self aliAuthorization];
}
- (void)clickCard{
    UIAlertController *alert = [CommonView getCommonAlert:@"" message:@"取消绑定支付宝" ok:@"确定" cancel:@"取消" completed:^(NSInteger index) {
        if (index ==1) {  //取消绑定
            dispatch_async(dispatch_get_main_queue(), ^{
                 [self UntiedAliCard];
            });
        }
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 解绑支付宝
- (void)UntiedAliCard{
    [SVProgressHUD show];
    NSString *userToken = [BGMUser shareInstance].userToken;
    NSString *userId = [BGMUser shareInstance].userId;
    [BGMHTTP requestWithMethodName:@"alipay/deleteAlipay" parameters:@{@"userToken":userToken,@"usersId":userId} completion:^(BOOL success, NSError *error, NSDictionary *result) {
        [SVProgressHUD dismiss];
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if([code isEqualToString:@"200"]){
            self.aliInfo = nil;
            [self addAliPay];
        }else{
            NSString *msg = [NSString stringWithFormat:@"code = %@",[result objectForKey:@"code"]];
            [SVProgressHUD showErrorWithStatus:msg];
        }
    }];
    
}


//- (void)getURL:(NSString *)url{
////    alipays://platformapi/startapp?appId=20000067&url=URLencode（这是您自己的地址）
//    NSString *aliUrl = [NSString stringWithFormat:@"alipays://platformapi/startapp?appId=20000067&url=%@",[self URLEncodedString:url]];
//    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:aliUrl]];
//
//}

//- (NSString *)URLEncodedString:(NSString *)input
//{
//    NSString *outputStr =(__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, /* allocator */(__bridge CFStringRef)input,NULL, /* charactersToLeaveUnescaped */(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8);
//    return outputStr;
//}

#pragma mark 支付授权
- (void)aliAuthorization{
    APAuthInfo *authInfo = [APAuthInfo new];
    authInfo.pid = @"2088331238010847";
    authInfo.appID = @"2018110662009351";
    authInfo.targetID = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];

    // 将授权信息拼接成字符串
    NSString *authInfoStr = [authInfo description];
    NSString *sign = @"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCy+iEfAnURbl5SXKT9qYDvn9NrvNiNmodvscadx4XW85XDeDxOXcEkFQgUUmWYxEasd8kRZkpSTSqiMZQjOPLOBtqzz9/zTjZSoVA1rt6gW+LiPjGqOngkUpw8M4nZBZsIKd7XLUx1FywiWqrLi4k6fVmHIbuq2RVSHzc4vtudP0VlqJxSzGB2mLCu35HIYc9IFiIbzC8XEXsDPT3KxYTpIzmnK3J4ECYrsOMT7wY9RV4r6PN5IC9P9qKwgjC5sfvCihtrecZkMV2dmUAFZhHnRT5dSn7O5tv0LAu1mBgF1I4Jx1TCMIH6I/fBqUC2VDVyREY3Qu6diC9fDqyBK8VbAgMBAAECggEASHtN4I4RNQ76eeZ1FxmHUwPqDk67cJVtVgmsAwfjpwqc0z2lRqNnbaJq1DgOVxDeAki8kCRZ4vzHUEo90QnmIxPZjEqaSqGZFFup7SO1m0G7H57KZEMrlqIyDZtdrxs7DtJOIdyBg0XwJLWNR8Npvts236gEpYsmvExSA9Qfgo2IcNP0eY1K0FfbQKRQoJCGKRMeCPgP0kFirK/Mi/hOXVf4toojnCG5Ep04U9R539fbzaKBBLkJ2YHZvJx2eXnCo0SazFZ9lsqtkouY0QtHB4QkvvQHS04VmE3kCWyD4H1nePnvEYpIMgN9wReim0Bq2LmVV5cZqeoxBfe2QhYtSQKBgQDjQEguo5Ly8s/cxNwjwQw2YvrHQZChzO88BXaxXaPwBYvnKJ48feC2wT9IPFEHV5/i2Vj9DnQ/ZLKceaR5xy3F5QC1QJc1F6w4TVNawygcQ3MCssibd/WBnWvd72oZyVAl8auaIdCxg93gssWO8ra6BfjS6AY/BQhNq3LX6SccHQKBgQDJnnPGOY/KJzrZwSPf4AcV/Z93tfl0IZUQ8+7CGIhGBYLL0dAGAgEp/Ax5C0ot9rsokcQb9tk1GcADpOi9EqIv+MN0VlXDkXuGlfgtuoAqS+Q/jV7h3sucduABaWKTxRMo4kNy1K2d+Y+jjtA2ppAVaUzs7+C5RRs455S6ra191wKBgDoNo+L2OoYB7YPybmJb4KjMJFBeuXn8BmmI48dvqn+YiyLkR3ggmBVXzLjBX9nGUrv61jbfSGchbFd448GQVmslk0a6V2Ziw8YmStL24/pEaM8ZqRG+VWNlObcagDpSKT1oPXREizGuBDJwuPNJodBn0ibeyymyOWrOD6qEj08pAoGADv0AjlPpJJYWAeohyJrW7AOWv0d/6+ozMrdvoG5CczIlrxFB7bBodb6PDtCQCyq0byem9I09SH1JkPvJcYTZGcfcf+GLLqa6EB9F++BJdtt9dFwGGbR+XntX28MB2QplijyH1xmIbp4G15neULHBNFZHqbWLdzpz858Dp30R0LECgYAdRCXCQzMQ65jQ72vILLmWBOJkGlY5y4yrkMn9XLFxF3NqW1jaTqTrsWyy+2hPAP4c+7cY7lJJzN6x1JsZZxIWHSG9rBlgfJ2UISmQzBaOT5xMz5vFZa3yoFz2j3OAmcPMsh/H4dmDRo4HizIIxPslsZAR8oSMV198SjHBXZRqFA==";

    authInfoStr = [NSString stringWithFormat:@"%@&sign=%@&sign_type=%@", authInfoStr, sign, @"RSA2"];
    [[AlipaySDK defaultService] auth_V2WithInfo:authInfoStr fromScheme:@"com.suyou.banggemang" callback:^(NSDictionary *resultDic) {
        // 解析 auth code
        NSString *code = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
        if ([code isEqualToString:@"9000"]) {
            NSString *result = resultDic[@"result"];
            [self getAlipayAuthCode:result];
        }
     
    }];

}
- (void)getAlipayAuthCode:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@"&"];
    NSString *str1 = [array objectAtIndex:3];
    str1 = [str1 stringByReplacingOccurrencesOfString:@"auth_code=" withString:@""];
    self.auth_code = str1;
    [self postAuthCode];
}
//向后台发送授权码
- (void)postAuthCode{
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"usersId":[BGMUser shareInstance].userId,@"code":self.auth_code};
    [BGMHTTP requestWithMethodName:@"alipay/openauth" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        [self getUserMenoy];
    }];
}

#pragma mark 提现、明细

- (void)tapClickBtn:(UITapGestureRecognizer *)getsture{
    BGMShareButton *btn = (BGMShareButton *)getsture.view;
    int tag = (int)btn.tag;
    if (tag == 100) {  //明细
        WalletDetailsViewController *vc = [[WalletDetailsViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (tag == 102){ //提现
        if(self.aliInfo != nil ){
            float moeny = [self.money floatValue];
            if(moeny > 0){
                WalletWithdrawViewController *vc = [[WalletWithdrawViewController alloc]init];
                vc.money = self.money;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
               [SVProgressHUD showInfoWithStatus:@"太穷啦！没有钱可以取"];
            }
        }else{
            [SVProgressHUD showInfoWithStatus:@"请绑定您的支付宝账号"];
        }
    }
    
}


@end
